import React from 'react';
import {sessionManager} from '../../utils/sessionStorage';
import {Form ,Row ,Col, Select ,Button ,DatePicker } from 'antd';
import Grid from '../../components/table/grid';
import StatisticsBox from '../../components/box/statistics';
import {injectIntl} from 'react-intl';
import {getYear} from '../../utils/Array';
import axios from "axios";
import qs from 'qs';
import moment from 'moment';

const FormItem = Form.Item;
const createForm = Form.create;
const Option = Select.Option;
const { RangePicker } = DatePicker;
const {MonthPicker} = DatePicker;


class timeSharing extends React.Component {
    constructor(props) {
        super(props);
        this.common = this.props.intl.messages.common;
        this.state={
            params:{
                dateType:'1',
                date: moment().format('YYYY')
            },
            boxParams:[],
            refresh:0
        };
        this.columns = [
            {
                title: '电站名称',
                dataIndex: 'groupName',
                key: 'groupName',
            },
            {
                title: '峰时电量（度）',
                dataIndex: 'peakPower',
                key: 'peakPower',
            },
            {
                title: '谷时电量（度）',
                dataIndex: 'valleyPower',
                key: 'valleyPower',
            },
            {
                title: '平时电量（度）',
                dataIndex: 'flatPower',
                key: 'flatPower',
            },
            {
                title: '尖时电量（度）',
                dataIndex: 'tipPower',
                key: 'tipPower',
            },
            {
                title: '合计',
                dataIndex: 'totalPower',
                key: 'totalPower',
            },
        
        ]
    }

    componentDidMount() {

    }

    transformData=(data)=>{
        data.list.forEach((k,v)=>(k.id=v));
        this.setBoxParams(data.summary);
        return data.list;
    }

    setBoxParams=(params)=>{
        console.log('params',params);
        this.setState({
            boxParams:[
                {
                    num:params.peakPower,
                    desc:"峰时电量（度）"
                },
                {
                    num:params.valleyPower,
                    desc:"谷时电量（度）"
                },
                {
                    num:params.flatPower,
                    desc:"平时电量（度）"
                },
                {
                    num:params.tipPower,
                    desc:"尖时电量（度）"
                },
                {
                    num:params.totalPower,
                    desc:"合计（度）"
                },
            ]
        })
    }

    handleChange = (value) => {
        console.log(`selected ${value}`);
        this.setState({
            params: Object.assign(this.state.params, {dateType: value})
        })
    };

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!!err) {
                return;
            }
            for (let key in values) {
                console.log(key);
                if (key === 'year') {
                    values.date = values[key];
                }
                if (key === 'month') {
                    values.date = values[key].format('YYYYMM');
                    delete values[key];
                }
                if (key === 'day') {
                    values.date = values[key].format('YYYYMMDD')
                    delete values[key];
                }
                if (key === 'selfDefining') {
                    values.startDate = values[key][0].format('YYYYMMDD');
                    values.endDate = values[key][1].format('YYYYMMDD');
                    delete values[key];
                }
            }
            this.setState({
                params: values,
                refresh: this.state.refresh + 1
            })
        });
    };


    render() {
        const token=JSON.parse(sessionStorage.getItem("token")||{}).token;
        let locale=sessionManager.get('locale');
        let exportQs=`${qs.stringify(this.state.params)}&token=${token}&locale=${locale}`;
        console.log('exportQs',exportQs);
        const {getFieldDecorator} = this.props.form;
        const monthFormat = 'YYYY/MM';
        const dateFormat = 'YYYY/MM/DD';

        const config = {
            rules: [
                {
                    required: true,
                    message: this.common.required
                }
            ]
        };

        return (
            <div>
                <form form={this.props.form} className="SC-form">
                    <Row gutter={24} type="flex">
                    <Col xl={3}>
                            <FormItem
                            >
                                {getFieldDecorator('dateType', {
                                    initialValue: this.state.params.dateType
                                })(
                                    <Select placeholder={'报表类型'} onChange={this.handleChange}>
                                        <Option value="1">年报表</Option>
                                        <Option value="2">月报表</Option>
                                        <Option value="3">日报表</Option>
                                        <Option value="4">自定义报表</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col xl={this.state.params.dateType == 4 ? 6 : 4}>
                            <FormItem
                            >
                                {this.state.params.dateType == 1 && getFieldDecorator('year', {
                                    rules: [{
                                        required: true,
                                        message: this.common.required
                                    }
                                    ],
                                    initialValue: moment().format('YYYY')
                                })(
                                    <Select placeholder={'年份'} style={{width: 150}}>
                                        {getYear().map((k, i) => {
                                            return <Option value={k} key={i}>{k}</Option>
                                        })}
                                    </Select>
                                )}
                                {this.state.params.dateType == 2 && getFieldDecorator('month', config)(
                                    <MonthPicker format={monthFormat} allowClear={false}/>
                                )}
                                {this.state.params.dateType == 3 && getFieldDecorator('day', config)(
                                    <DatePicker format={dateFormat} allowClear={false}/>
                                )}
                                {this.state.params.dateType == 4 && getFieldDecorator('selfDefining', config)(
                                    <RangePicker format={dateFormat} allowClear={false}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col>
                            <FormItem>
                                <Button type="primary" htmlType="submit"
                                        onClick={this.handleSubmit} className="ant-btn-84">{this.common.search}</Button>
                                <a href={`${axios.defaults.baseURL}/api/statistics/stubGroup/timeSharing/export?${exportQs}`}>
                                    <Button type="primary">{this.common.exportStatement}</Button>
                                </a>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <StatisticsBox params={this.state.boxParams}/>
                <Grid columns={this.columns} params={this.state.params} 
                      url={'/api/statistics/stubGroup/timeSharing/qry'} refresh={this.state.refresh}/>
            </div>
        )
    }
}

timeSharing = createForm()(timeSharing);
export default injectIntl(timeSharing)
